// pages/addressAdd/addressAdd.js
Page({
    data: {
      formData: {
        consignee: '',
        phone: '',
        region: ['', '', ''],
        detail: '',
        isDefault: false,
        id: null // 用于编辑时存储地址ID
      },
      isEdit: false // 是否为编辑模式
    },
  
    onLoad(options) {
      // 如果页面是通过编辑按钮跳转过来的，会带有 addressId 参数
      if (options.addressId) {
        this.setData({ isEdit: true });
        // 动态修改导航栏标题
        wx.setNavigationBarTitle({
          title: '编辑收货地址'
        });
        // 加载要编辑的地址数据
        this.loadAddressForEdit(options.addressId);
      }
    },
  
    /**
     * 加载要编辑的地址数据并回显到表单
     */
    loadAddressForEdit(addressId) {
      const addressList = wx.getStorageSync('addressList') || [];
      const addressToEdit = addressList.find(item => item.id == addressId);
  
      if (addressToEdit) {
        this.setData({
          formData: {
            consignee: addressToEdit.consignee,
            phone: addressToEdit.phone,
            region: [addressToEdit.province, addressToEdit.city, addressToEdit.district],
            detail: addressToEdit.detail,
            isDefault: addressToEdit.isDefault || false,
            id: addressToEdit.id // 关键：保存原ID
          }
        });
      }
    },
  
    handleInput(e) {
      const { key } = e.currentTarget.dataset;
      const { value } = e.detail;
      this.setData({
        [`formData.${key}`]: value
      });
    },
  
    handleRegionChange(e) {
      const { value } = e.detail;
      this.setData({
        'formData.region': value
      });
    },
    
    handleDefaultChange(e) {
      const { value } = e.detail;
      this.setData({
        'formData.isDefault': value
      });
    },
  
    /**
     * 表单验证
     */
    validateForm() {
      const { formData } = this.data;
      if (!formData.consignee.trim()) {
        wx.showToast({ title: '请输入收货人姓名', icon: 'none' });
        return false;
      }
      if (!/^1[3-9]\d{9}$/.test(formData.phone.trim())) {
        wx.showToast({ title: '请输入正确的手机号码', icon: 'none' });
        return false;
      }
      if (formData.region.some(item => !item.trim())) {
        wx.showToast({ title: '请选择所在地区', icon: 'none' });
        return false;
      }
      if (!formData.detail.trim()) {
        wx.showToast({ title: '请输入详细地址', icon: 'none' });
        return false;
      }
      return true;
    },
  
    /**
     * 提交地址（新增或更新）
     */
    submitAddress() {
      if (!this.validateForm()) return;
  
      const { formData, isEdit } = this.data;
      const addressList = wx.getStorageSync('addressList') || [];
  
      // 构造地址对象
      const address = {
        consignee: formData.consignee.trim(),
        phone: formData.phone.trim(),
        province: formData.region[0],
        city: formData.region[1],
        district: formData.region[2],
        detail: formData.detail.trim(),
        isDefault: formData.isDefault,
        id: isEdit ? formData.id : Date.now() // 编辑则使用原ID，新增则用时间戳作为ID
      };
  
      // 如果设为默认地址，需要将其他地址的默认状态取消
      if (address.isDefault) {
        for (let i = 0; i < addressList.length; i++) {
          addressList[i].isDefault = false;
        }
      }
  
      let newAddressList = [];
      if (isEdit) {
        // 编辑模式：找到并替换原地址
        newAddressList = addressList.map(item => item.id == address.id ? address : item);
      } else {
        // 新增模式：添加到列表末尾
        newAddressList = [...addressList, address];
      }
  
      // 保存到本地缓存
      wx.setStorageSync('addressList', newAddressList);
  
      // 显示成功提示并返回上一页
      wx.showToast({
        title: isEdit ? '地址更新成功' : '地址添加成功',
        icon: 'success'
      });
  
      setTimeout(() => {
        wx.navigateBack({
          delta: 1
        });
      }, 1500);
    }
  });